package com.shiguiwu.springmybatis.leetcode;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * @description: 计算题
 * @author: stone
 * @date: Created by 2022/8/10 10:34
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.leetcode
 * <p>
 * 求解一个给定的方程，将x以字符串 "x=#value" 的形式返回。该方程仅包含 '+' ， '-' 操作，变量 x 和其对应系数。
 * <p>
 * 如果方程没有解，请返回 "No solution" 。如果方程有无限解，则返回 “Infinite solutions” 。
 * <p>
 * 题目保证，如果方程中只有一个解，则 'x' 的值是一个整数。
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/solve-the-equation
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
@Slf4j
public class SolveEquation {

    public static void main(String[] args) {
        log.info("切割字符串 ===> {}", Integer.parseInt("+1"));
        SolveEquation s = new SolveEquation();
        String result = s.solveEquation("3x=33+22+11");//"x=-1"   "x+5-3+x=6+x-2"
        log.info("计算结果为： {}", result);
    }


    public String solveEquation(String equation) {
        String[] split = equation.replaceAll("-", "+-").split("=");

        int[] left = resolveExpression(split[0]);
        int[] right = resolveExpression(split[1]);
        int c = right[0] - left[0];
        int x = left[1] - right[1];
        if (x == 0) {
            return c == 0 ? "Infinite solutions" : "No solution";
        }

        return "x=" + c / x;
    }

    private int[] resolveExpression(String expression) {

        String[] split = expression.split("\\+");

        //记录一下符号
        //String x1 = "";
        //String x2 = "";
        //String x3 = "";
        int sum1 = 0;
        int sum2 = 0;
        for (int i = 0; i < split.length; i++) {
            if (split[i].contains("x")) {
                //x3 = x1 + 1;
                sum2 += Integer.parseInt(split[i].substring(0, split[i].length() - 1));

            }

            if (split[i].matches("\\d+")) {
                //x2 = x1 + split[i];
                sum1 += Integer.parseInt(split[i]);


            }
        }

        return new int[]{sum1, sum2};

    }


}
